package com.example.demo.utils.http;


import com.example.demo.base.BuildConfig;
import okhttp3.*;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

public class HttpClient {

    public static Retrofit getInstance() {
        return RetrofitHolder.holder;
    }

    private static class RetrofitHolder {
        private static Retrofit holder = createdRetrofit();
    }


    private static Retrofit createdRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
//                .addConverterFactory(ScalarsConverterFactory.create())
                .client(getOKClient())
                .build();
    }


    private static OkHttpClient getOKClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        /**
//         *设置缓存
//         */
//        final File chachefile = new File("CacheFilePath");
//        final Cache cache = new Cache(chachefile, 1024 * 1024 * 50);//缓存文件
//        Interceptor cacheInterceptor = new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request request = chain.request();
//                if (!AppUtils.isNetworkReachable(AppAplication.getContext())) {
//                    request = request.newBuilder()
//                            .cacheControl(CacheControl.FORCE_CACHE)
//                            .build();
//                }
//                Response response = chain.proceed(request);
//                if (AppUtils.isNetworkReachable(AppAplication.getContext())) {
//                    int maxAge = 0;
//                    // 有网络时 设置缓存超时时间0个小时
//                    response.newBuilder()
//                            .header("Cache-Control", "public, max-age=" + maxAge)
//                            .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
//                            .build();
//                } else {
//                    //无网络时，设置超时为4周
//                    int maxStale = 60 * 60 * 24 * 28;
//                    response.newBuilder()
//                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
//                            .removeHeader("Pragma")
//                            .build();
//                }
//                return response;
//            }
//        };
//        builder.cache(cache).addInterceptor(cacheInterceptor);

        /**
         *公共参数
         */
//        Interceptor addQueryParameterInterceptor = new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request originalRequest = chain.request();
//                Request request;
//                String method = originalRequest.method();
//                Headers headers = originalRequest.headers();
//                HttpUrl modifiedUrl = originalRequest.url().newBuilder()
//                        // Provide your custom parameter here
//                        .addQueryParameter("platform", "adnroid")
//                        .addQueryParameter("version", "1.2.0")
//                        .build();
//                request = originalRequest.newBuilder().url(modifiedUrl).build();
//                return chain.proceed(request);
//            }
//        };
//        builder.addInterceptor(addQueryParameterInterceptor);

        /**
         * 设置请求头
         */
        Interceptor headerInterceptor = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Request orignaRequest = chain.request();
                Request request = orignaRequest.newBuilder()
                        .header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
//                        .header("AppType", "TPOS")
//                        .header("Content-Type", "application/x-www-form-urlencoded")
////                        .header("Content-Type", "application/json")
//                        .header("Accept", "application/json")
                        .method(orignaRequest.method(), orignaRequest.body())
                        .build();
                return chain.proceed(request);
            }
        };
        builder.addInterceptor(headerInterceptor);

        /**
         * Log信息拦截器
         */
        //compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
        if (BuildConfig.DAIYU_DEBUG) {
            //log信息拦截器
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor("HTTP");
            httpLoggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
            httpLoggingInterceptor.setColorLevel(Level.INFO);
            //设置Debug Log模式
            builder.addInterceptor(httpLoggingInterceptor);
        }

        /**
         * 设置cookie
         */
        //compile 'com.squareup.okhttp3:okhttp-urlconnection:3.4.1'
//        CookieManager cookieManager = new CookieManager();
//        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
//        builder.cookieJar(new JavaNetCookieJar(cookieManager));
        /**
         * 设置超时和重连
         */
        //设置超时
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        builder.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS));
        //错误重连
        builder.retryOnConnectionFailure(true);
        return builder.build();
    }

}
